package main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
)

func main() {

	db := DB.Session(&gorm.Session{
		Logger: mysqlLogger, //看SQL
	})

	{ //快速查询
		stu := Student{} //注意，既可以作为接收体，也可以作为查询条件
		//err := db.First(&stu, 2).Error //SELECT * FROM `t_student` WHERE `t_student`.`id` = 2 ORDER BY `t_student`.`id` LIMIT 1
		//err := db.Last(&stu, 2).Error //SELECT * FROM `t_student` WHERE `t_student`.`id` = 2 ORDER BY `t_student`.`id` DESC LIMIT 1
		//err := db.Take(&stu, 2).Error //SELECT * FROM `t_student` WHERE `t_student`.`id` = 2 LIMIT 1
		err := db.Find(&stu, 2).Error //SELECT * FROM `t_student` WHERE `t_student`.`id` = 2
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				fmt.Println("未查到数据")
			} else {
				fmt.Println(err.Error())
			}
		} else {
			fmt.Println("first:", stu)
		}
	}

	//说明：Scan会判断单数还是复数，单数就scan一个，复数是所有
	{ //原生SQL
		student := Student{}
		raw := db.Raw("select * from t_student where id=?", 2)
		fmt.Println("---") //本行说明，Raw不会执行，Scan后才会执行

		tx := raw.Scan(&student)
		if tx.Error != nil {
			fmt.Println(tx.Error.Error())
		} else {
			fmt.Println(student)
		}
	}

	{ //原生SQL 切片
		var ss []Student
		raw := db.Raw("select * from t_student where id > ?", 2)
		fmt.Println("---") //本行说明，Raw不会执行，Scan后才会执行

		tx := raw.Scan(&ss)
		if tx.Error != nil {
			fmt.Println(tx.Error.Error())
		} else {
			fmt.Println(ss)
			for _, s := range ss {
				fmt.Println(s)
			}
		}
	}

	{
		//student := Student{ID: 3}
		//DB.Count(&student)
	}

}
